package com.c.ctgproject.ui.sell.material

import android.app.Activity
import android.content.Intent
import android.os.Environment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.c.ctgproject.R
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.customview.GlideImageLoader
import com.c.ctgproject.customview.ImagePickerLoader
import com.c.ctgproject.mode.MyConstants
import com.c.ctgproject.utils.CustomToast
import com.c.ctgproject.utils.MyLog
import com.c.ctgproject.utils.handlerNull
import com.c.ctgproject.utils.initData
import com.google.gson.Gson
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.imagepicker.data.ImagePickType
import com.lwkandroid.widget.ninegridview.NineGirdImageContainer
import com.lwkandroid.widget.ninegridview.NineGridBean
import com.lwkandroid.widget.ninegridview.NineGridView
import com.nanchen.compresshelper.CompressHelper
import kotlinx.android.synthetic.main.activity_sale_apply.*
import kotlinx.android.synthetic.main.activity_sale_apply.mPhotoNGV
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 *作者:LiBW
 *创建日期: 2020/9/7
 *描述: 物料销售申请页面 规格及质量/数量为非必填
 */
class SaleApplyActivity : BaseActivity() {
    private val mViewModel: SaleApplyViedModel by lazy { ViewModelProvider(this)[SaleApplyViedModel::class.java] }
    private val imageShowList = ArrayList<String>()

    //已经处理过的图片地址
    private val imageFiles = ArrayList<File>()

    private val requestCodePicker = 1001


    override fun event() {
        changeTransparentStatusBar()
        changeStatusIconColor(true)
        mPartNameTV.text = intent.getStringExtra(MyConstants.MATERIAL_NAME).handlerNull()
        mMaterialWeightTV.text = intent.getStringExtra(MyConstants.MATERIAL_WEIGHT).handlerNull()
        initPhoto()
        mViewModel.applyResult.observe(this, Observer {
            loading.dismiss()
            MyLog.d(it)
            val data = initData(it)
            if (data.status == 0) {
                CustomToast.showToast(this, "提交成功")
                finish()
            } else {
                CustomToast.showToast(this, data.msg.handlerNull())
            }
        })
        mViewModel.error.observe(this, Observer {
            loading.dismiss()
            CustomToast.showToast(this, it)
        })

    }

    override fun click() {
        //确认
        mConfirmRL.setOnClickListener {
            editTextCheck()
        }
    }

    private fun editTextCheck() {
        val SQYXSZL = mSQYXSZL.text.toString()
        val XSDJ = mXSDJ.text.toString()
        val GHDWGR = mGHDWGR.text.toString()
        val AddressET = mAddressET.text.toString()
        val SWDJH = mSWDJH.text.toString()
        val CWJSFS = mCWJSFS.text.toString()
        val phoneNumber = mPhoneNumET.text.toString()
        val SQYXSSL = mSQYXSSL.text.toString()
        val GGJZZ = mGGJZZ.text.toString()
        val materialId = intent.getIntExtra(MyConstants.MATERIAL_ID, 0)

        when {
            SQYXSZL.isEmpty() -> CustomToast.showToast(this, "请填写预销售重量")
            XSDJ.isEmpty() -> CustomToast.showToast(this, "请填写销售单价")
            GHDWGR.isEmpty() -> CustomToast.showToast(this, "请填写购货单位/个人")
            AddressET.isEmpty() -> CustomToast.showToast(this, "请填写地址")
            SWDJH.isEmpty() -> CustomToast.showToast(this, "请填写税务登记号(身份证号)")
            phoneNumber.isEmpty() -> CustomToast.showToast(this, "请输入电话号码")
            CWJSFS.isEmpty() -> CustomToast.showToast(this, "请输入财务结算方式")
            imageShowList.isEmpty() -> CustomToast.showToast(this, "请至少上传一张照片")
            else -> {
                //处理图片
                imageFiles.clear()
                imageShowList.forEach {
                    if (!it.startsWith("http")) {
                        val file = File(it)
                        val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
                        imageFiles.add(newFile)
                    }
                }

                val map: MutableMap<String, Any> = HashMap()
                //物料ID
                map["materialId"] = materialId
                //预计销售重量（吨）
                map["planSalesWeight"] = SQYXSZL
                //预计销售数量
                map["planSalesNumber"] = SQYXSSL
                //销售单价（元）
                map["salesPrice"] = XSDJ
                //规格及质量
                map["remark"] = GGJZZ
                //购货单位/个人
                map["purchaser"] = GHDWGR
                //地址
                map["address"] = AddressET
                //税务登记号/身份证号
                map["identity"] = SWDJH
                //电话
                map["phoneNumber"] = phoneNumber
                //财务结算方式
                map["financialSettlementWay"] = CWJSFS
                //合同号
                map["contractNo"]=mHTH.text.handlerNull()



                val obj = Gson().toJson(map)
                val body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), obj)

                mViewModel.saleApply(filesToMultipartBodyParts(imageFiles, map))
                loading.show()
            }
        }
    }


    private fun filesToMultipartBodyParts(pictureFile: ArrayList<File>, map: MutableMap<String, Any>): ArrayList<MultipartBody.Part> {
        val parts: ArrayList<MultipartBody.Part> = ArrayList()
        for (i in pictureFile) {
            MyLog.d("上传文华图片的名字${i.name}")
            toRequestBodyOfImage("image", i)?.let { parts.add(it) }
        }
        map.forEach { m ->
            toRequestBodyOfText(m.key, m.value.handlerNull())?.let { parts.add(it) }
        }
        return parts
    }

    private fun toRequestBodyOfImage(keyStr: String, pFile: File): MultipartBody.Part? {
        val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), pFile)
        return MultipartBody.Part.createFormData(keyStr, pFile.name, requestBody)
    }

    private fun toRequestBodyOfText(keyStr: String, value: String): MultipartBody.Part? {
        return MultipartBody.Part.createFormData(keyStr, value)
    }

    private fun initPhoto() {
        //设置图片加载器，这个是必须的，不然图片无法显示
        mPhotoNGV.setImageLoader(GlideImageLoader())
        //设置显示列数，默认3列
        mPhotoNGV.setColumnCount(3)
        //设置是否为编辑模式，默认为false
        mPhotoNGV.setIsEditMode(true)
        //设置单张图片显示时的尺寸，默认100dp
        mPhotoNGV.setSingleImageSize(150)
        //设置单张图片显示时的宽高比，默认1.0f
        mPhotoNGV.setSingleImageRatio(0.8f)
        //设置最大显示数量，默认9张
        mPhotoNGV.setMaxNum(2)
        //设置图片显示间隔大小，默认3dp
        mPhotoNGV.setSpcaeSize(4)
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        //设置删除图片
        //        mNineGridView.setIcDeleteResId(R.drawable.ic_block_black_24dp);
        //设置删除图片与父视图的大小比例，默认0.25f
        mPhotoNGV.setRatioOfDeleteIcon(0.15f)
        //设置“+”号的图片
        mPhotoNGV.setIcAddMoreResId(R.drawable.ic_ngv_add_pic)
        //设置各类点击监听
        mPhotoNGV.setOnItemClickListener(object : NineGridView.onItemClickListener {
            override fun onNineGirdItemDeleted(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {
                if (imageShowList.isNotEmpty()) {
                    imageShowList.removeAt(position)
                }
            }

            override fun onNineGirdItemClick(position: Int, gridBean: NineGridBean?, imageContainer: NineGirdImageContainer?) {

            }

            override fun onNineGirdAddMoreClick(cha: Int) {
                //编辑模式下，图片展示数量尚未达到最大数量时，会显示一个“+”号，点击后回调这里
                val imageLoader = ImagePicker()
                    .cachePath(Environment.getExternalStorageDirectory().absolutePath)
                    .pickType(ImagePickType.MULTI)
                    .displayer(ImagePickerLoader())
                    .maxNum(cha)
                    .start(this@SaleApplyActivity, requestCodePicker)
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == requestCodePicker && resultCode == Activity.RESULT_OK && data != null) {
            val list: List<ImageBean> = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
            val resultList: MutableList<NineGridBean> = java.util.ArrayList()
            for (imageBean in list) {
                val nineGirdData = NineGridBean(imageBean.imagePath)
                imageShowList.add(imageBean.imagePath)
                resultList.add(nineGirdData)
            }
            mPhotoNGV.addDataList(resultList)
        }
    }
    override fun getLayout() = R.layout.activity_sale_apply
}